package edu.hznu.retroSnakerPlanServer.entity;

import edu.hznu.retroSnakerPlanServer.service.ByteSerializable;
import edu.hznu.retroSnakerPlanServer.utils.ByteUtils;

/**
 * create by Cliven on 2018-05-31 15:56
 *
 * @author Cliven
 * 食物
 */
public class Food implements ByteSerializable {
    private Integer x;
    private Integer y;
    private Integer colorType;

    public static final int SIZE = 5;

    /**
     * 获取实例
     *
     * @param array  获取实例的字节数组
     * @param offset 偏移量
     * @return 实例
     * @author Cliven
     * @since 2018-05-31 20:42:41
     */
    public static Food getInstance(Byte[] array, int offset) {
        if ((offset + SIZE) > array.length) {
            throw new IllegalArgumentException("Out of Food range...");
        }
        Food food = new Food();
        food.setX(ByteUtils.byteToShortInteger(array, offset));
        offset += 2;
        food.setY(ByteUtils.byteToShortInteger(array, offset));
        offset += 2;
        return food.setColorType(array[offset] & 0xFF);
    }

    public Food() {
    }

    public Integer getX() {
        return x;
    }

    public Food setX(Integer x) {
        this.x = x;
        return this;
    }

    public Integer getY() {
        return y;
    }

    public Food setY(Integer y) {
        this.y = y;
        return this;
    }

    public Integer getColorType() {
        return colorType;
    }

    public Food setColorType(Integer colorType) {
        this.colorType = colorType;
        return this;
    }

    /**
     * 序列化某个对象为byte数组
     *
     * @return 字节数组
     * @author Cliven
     * @since 2018-6-1 08:14:24
     */
    @Override
    public Byte[] serial() {
        Byte[] res = new Byte[SIZE];
        int offset = 0;

        res[offset++] = (byte) (this.x & 0xFF);
        res[offset++] = (byte) ((this.x >> 8) & 0xFF);

        res[offset++] = (byte) (this.y & 0xFF);
        res[offset++] = (byte) ((this.y >> 8) & 0xFF);

        res[offset] = (byte) (this.colorType & 0xFF);
        return res;
    }

    @Override
    public String toString() {
        return "Food{" +
                "x=" + x +
                ", y=" + y +
                ", colorType=" + colorType +
                '}';
    }
}
